package com.deercrowing.takeaway.controller.admin;

import com.deercrowing.takeaway.common.constant.MessageConstant;
import com.deercrowing.takeaway.common.model.Result;
import com.deercrowing.takeaway.common.util.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    OssUtil ossUtil;

    @PostMapping("/upload")
    public ResponseEntity upload(MultipartFile file){
        log.info("文件上传：{}",file);

        try {
            String originalFilename = file.getOriginalFilename();// 文件名称
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + fileSuffix;

            String filePath = ossUtil.upload(file.getBytes(), objectName);
            return ResponseEntity.ok(Result.OK(filePath));
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return new ResponseEntity(MessageConstant.UPLOAD_FAILED,HttpStatus.BAD_REQUEST);
    }
}
